package com.ncepu.clubmanagement.service.impl;

import com.ncepu.clubmanagement.mapper.ClubManagementRelationMapper;
import com.ncepu.clubmanagement.mapper.ClubSelectionMapper;
import com.ncepu.clubmanagement.mapper.MessageMapper;
import com.ncepu.clubmanagement.pojo.Message;
import com.ncepu.clubmanagement.pojo.MessageFont;
import com.ncepu.clubmanagement.pojo.MessageLink;
import com.ncepu.clubmanagement.pojo.MessageMetaData;
import com.ncepu.clubmanagement.pojo.inter.IsClubManagerCheck;
import com.ncepu.clubmanagement.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ClubSelectionMapper clubSelectionMapper;

    @Autowired
    private ClubManagementRelationMapper clubManagementRelationMapper;


    @Override
    @Transactional
    public void sendMessageBySystem(MessageFont messageFont) {   // 此方法系统使用，没有权限判定
        // 换算为message对象插入消息体中
        Message message = messageFont.toMessage();
        messageMapper.insertMessage(message);
        // 获取消息链接并插入消息链接表中
        List<MessageLink> links = messageFont.toMessageLinks(clubId -> clubSelectionMapper.getPersonIdByClubId(clubId),
                message.getMessageId());
        // 插入数据
        messageMapper.insertMessageLinks(links);
    }

    @Override
    @Transactional
    public void sendMessage(MessageFont messageFont) throws Exception {
        // 换算为message对象插入消息体中
        Message message = messageFont.toMessage();
        messageMapper.insertMessage(message);
        // 获取消息链接并插入消息链接表中
        List<MessageLink> links = messageFont.toMessageLinksWithPermissionCheck(
                clubId -> clubSelectionMapper.getPersonIdByClubId(clubId),
                (IsClubManagerCheck) clubId -> clubManagementRelationMapper.isPersonIdExistByClubId(clubId,message.getSourcePersonId()),
                message.getMessageId()
        );
        // 插入数据
        messageMapper.insertMessageLinks(links);
    }


    @Override
    public void setMessageIsReadWithVerifyPermission(Integer messageId, Integer personId) {
        messageMapper.setMessageIsReadByMessageIdAndPersonId(messageId, personId);
    }

    @Override
    public String getMessageContent(Integer messageId, Integer targetPersonId) {

        String content = messageMapper.getMessageContentByMessageIdAndPersonId(messageId, targetPersonId);

        return content;
    }

    @Override
    public List<MessageMetaData> getMessageMetaDataList(Integer targetPersonId) {
        // 获取消息元数据列表
        List<MessageMetaData> ls = messageMapper
                .selectMessageMetaDataByTargetPersonId(targetPersonId);
        return ls;
    }


}
